<?php



class EscoreboarApi {

    public function grant($token){
        $developer= new Model_Developer();
        return $developer->exists($token);
    }

    private function replaceKey($item, $newKey, $oldKey){
        $item[$newKey]=$item[$oldKey];
        unset($item[$oldKey]);
        return $item;
    }

    public function createUser($tokenDeveloper, $email, $pass){
        if($this->grant($tokenDeveloper)){
            $user= new Model_Users();
            if($user->fetchUserByEmail($email))
                    return array("error"=> 3,"errorDescription"=>"This email is taken. Please use another one.");
            else{
                if($user->saveUser(array("email"=>$email,"password"=>$pass)))
                    return array("token"=>$user->getUserToken($email));
                else
                    return array("error"=> 1,"errorDescription"=>"invalid user.");
            }
        }else{
            return array("error"=> 2,"errorDescription"=>"invalid token.");
        }
    }
    public function login($tokenDeveloper,$email, $pass){
        if($this->grant($tokenDeveloper)){
            $user= new Model_Users();
            if($user->checkUserLogin($email, $pass))
                return array("token"=>$user->getUserToken($email));
            else
                return array("error"=> 1,"errorDescription"=>"Wrong email or password, please try again.");
        }else
            return array("error"=> 2,"errorDescription"=>"invalid token.");
    }

    public function getSports($tokenDeveloper){
        if($this->grant($tokenDeveloper)){
            $sports=new Model_Sports();
            return $sports->find();
        }else
            return array("error"=> 2,"errorDescription"=>"invalid token.");
    }

    public function createEvent($tokenDeveloper,$tokenUser, $sport, $startDate, $startTime, $competition, $location, $teams, $tags){
        
        if($this->grant($tokenDeveloper)){
            $event=new Model_Events();
            $user=new Model_Users();
            $u=$user->fetchUserByToken($tokenUser);


            if($event->exists($u['_id'], $sport, new MongoDate(strtotime($startDate." ".$startTime)), $competition, $location)){
                return array("error"=> 3,"errorDescription"=>"event already exists.");
            }else{
                $token=$event->create($sport, new MongoDate(strtotime($startDate." ".$startTime)), $competition, $location, explode("_",$teams), explode("_",$tags));
                if($token){
                    return array("token"=>current($token));
                }else
                    return array("error"=> 1,"errorDescription"=>"invalid event.");
            }

        }else
            return array("error"=> 2,"errorDescription"=>"invalid token.");
    }
    public function getEventStatic($user, $event){
        //TODO
    }

    public function getEvent($tokenDeveloper, $tokenEvent){
        if($this->grant($tokenDeveloper)){
            $event=new Model_Events();

            
            $e=$event->get($tokenEvent);

            unset($e['_id']);


            $e["st"]=date('Y-M-d h:i:s', $e["st"]->sec);
            $e=$this->replaceKey($e, "startTime", "st");
            $e=$this->replaceKey($e, "sport", "s");
            $e["lu"]=date('Y-M-d h:i:s', $e["lu"]->sec);
            $e=$this->replaceKey($e, "lastUpdate", "lu");
            $e=$this->replaceKey($e, "competition", "c");
            $e=$this->replaceKey($e, "location", "l");
            $e=$this->replaceKey($e, "participants", "ps");
            foreach($e['participants'] as $k=>$v){
                $nk="participant_".$k;
                $e['participants']=$this->replaceKey($e['participants'], $nk, $k);
            }

            $e=$this->replaceKey($e, "tags", "ts");
            foreach($e['tags'] as $k=>$v){
                $nk="tag_".$k;
                $e['tags']=$this->replaceKey($e['tags'], $nk, $k);
            }
            return $e;

        }else
            return array("error"=> 2,"errorDescription"=>"invalid token.");


    }
    //Devuelve las posible acciones a asociar al evento
    public function getActions($tokenDeveloper, $tokenEvent){
        if($this->grant($tokenDeveloper)){
            $event=new Model_Events();
            $actions=$event->getPossibleActions($tokenEvent);
            foreach($actions as $k=>$v){
                $nk="action_".$k;
                $actions=$this->replaceKey($actions, $nk, $k);
                $actions[$nk]=$this->replaceKey($actions[$nk], "name", "n");
                $actions[$nk]=$this->replaceKey($actions[$nk], "type", "t");
                $actions[$nk]=$this->replaceKey($actions[$nk], "value", "v");
            }
            return $actions;
        }else
            return array("error"=> 2,"errorDescription"=>"invalid token.");


    }
    public function _putAction($tokenEvent, $time, $team, $action){

        $event=new Model_Events();
        if($event->putAction($tokenEvent, $time, $action, $team))
            return array("ok"=>1);
        else
           return array("error"=> 3,"errorDescription"=>"invalid action.");
    }
    public function putAction($tokenDeveloper, $tokenEvent, $time, $team, $action){
        if($this->grant($tokenDeveloper)){
            $event=new Model_Events();
            if($event->putAction($tokenEvent, $time, $action, $team))
                return array("ok"=>1);
            else
                return array("error"=> 3,"errorDescription"=>"invalid action.");
        }else{
            return array("error"=> 2,"errorDescription"=>"invalid token.");
        }
    }
    public function removeAction($tokenDeveloper, $tokenEvent, $sequence){
        if($this->grant($tokenDeveloper)){
            $event=new Model_Events();
            if($event->removeAction($tokenEvent, $sequence))
                return array("ok"=>1);
            else
                return array("error"=> 3,"errorDescription"=>"invalid action.");
        }else{
            return array("error"=> 2,"errorDescription"=>"invalid token.");
        }
    }
    public function refreshEvent($tokenEvent, $part, $time, $running){

        $sports = Zend_Registry::get('sports');

        $events=new Model_Events();
        $event = $events->get($tokenEvent);
        if(isset($event['as'])){
            foreach ($event['as'] as $index=>$action)
            {
                $event['as'][$index]['an'] = ($action["a"]>-1)?$sports[$event['s']]["actions"]["action_".$action["a"]]["name"]:"";
                $event['as'][$index]['pn'] = $event['ps'][$action["p"]]["n"];
            }
        }
        
        if($running=="true"){
            $tm=array();
            if(!$events->updateTime($tokenEvent, $part, $time))
                    die("Updating time");
            //Si el tiempo es 0 significa que se esta marcando como parte finalizada
            //Se crea la acción con id=-1
            if($time==0)
                $this->_putAction($tokenEvent, $time, 0, -1);
            
        }else{
            $part=count($event['tm']);
            $time=$event['tm'][$part-1];
            $tm=array("part"=>$part, "time"=>$time);
        }
        $part=count($event['tm']);
        $sport=$events->getSport();
        

        $start=count($sport['parts'])>=$part;
        $pause=$running=="true" && $time>0;
        $part=$part==0?1:$part;
        $end=$time>0 && $event['tm'][$part-1]>(($sport['parts']['part_'.($part-1)]['duration']*60)*0.8);
        $finished=$part>count($sport['parts']);

        return array("ps"=>$event['ps'],"as"=>(isset($event['as'])?$event['as']:array()), "start"=>$start, "end"=>$end, "pause"=>$pause, "finished"=>$finished, "tm"=>$tm);
    }

    public function recentEvents() {
        $event=new Model_Events();
        $ret = $event->recentEvents(5);
        for ($i=0; $i<count($ret); $i++)
            $ret[$i]["_id"] = $ret[$i]["_id"]->__toString();
        return $ret;
    }
}
